/**
 * 渲染单元格
 */
import {NAME} from "@/store/elements";
import {DISPLAY, WIDGET} from "@/store/elementui";

function render (h, column, row) {
  const name = column[NAME]

  const display = column[DISPLAY]

  const value = name ? row[name] : undefined

  if (!display) return spanCell(h, {}, value)

  let { widget, definition }  = (typeof display === 'string') ? {
    widget: display,
    definition: {}
  } : {
    widget: display[WIDGET],
    definition: display
  }

  switch (widget) {
    case 'bool' : return boolCell(h, definition, value)

    case 'url': return urlCell(h, definition, value, row)

    default: return spanCell(h, definition, value)
  }
}

function spanCell (h, definition, value) {
  return h('span', {
    attrs: definition
  },  value + '')
}

function boolCell (h, definition, value) {
  let { icons, styles = [], texts = ['否', '是'] } = definition

  if (!icons) return spanCell(h, {}, texts[+value])

  return h(
    'i',
    {
      'class': icons[value],
      style: styles[value],
      attrs: {
        ...definition
      }
    }
  )
}

function urlCell(h, definition, value, row = {}) {
  let { relation, text } = definition;

  let label = relation ? row[relation] : (text ?? '下载')

  return h('a', {
    attrs: {
      href: value,
      target: '_blank',
      ...definition
    },
  }, label)
}

export default render
